package com.skivingcloud.file.controller;


import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.skivingcloud.admin.sys.entity.User;
import com.skivingcloud.admin.utils.UserUtil;
import com.skivingcloud.common.utils.DateUtils;
import com.skivingcloud.common.utils.PageUtils;
import com.skivingcloud.common.utils.R;
import com.skivingcloud.file.entity.SysFile;
import com.skivingcloud.file.service.ISysFileService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * <p>
 * 附件 前端控制器
 * </p>
 *
 * @author skivingcloud
 * @since 2022-03-02
 */
@RestController
@RequestMapping("/file")
public class SysFileController {

	private static Logger log = LoggerFactory.getLogger(SysFileController.class);

	@Autowired
	private ISysFileService sysFileService;

	/**
	 * 分页查询
	 * 
	 * @param params
	 * @return
	 */
	@PostMapping("/list")
	public R list(@RequestBody Map<String, Object> params) {
		try {
			PageUtils page = sysFileService.queryPage(params);
			return R.ok().put("page", page);
		} catch (Exception e) {
			log.error("查询文件列表失败list", e);
			return R.error("查询文件列表失败");
		}
	}

	/**
	 * 文件上传，使用formData.append('file', val.raw)来上传文件
	 * 
	 * @param request
	 * @return
	 */
	@PostMapping("/improtCommon")
	public R improtCommon(HttpServletRequest request) {
		try {
			User user = UserUtil.getUser();
			StandardServletMultipartResolver resolver = new StandardServletMultipartResolver();
			MultipartHttpServletRequest mhr = resolver.resolveMultipart(request);
			List<MultipartFile> files = mhr.getFiles("file");
			String businessId = request.getParameter("businessId");
			List<String> fileIds = sysFileService.saveFiles(files, businessId, user);
			return R.ok().put("fileIds", fileIds);
		} catch (Exception e) {
			log.error("上传文件失败", e);
			return R.error("上传文件失败");
		}
	}

	/**
	 * 文件下载
	 * 
	 * @param id       文件记录id
	 * @param response
	 * @return
	 */
	@RequestMapping("/downloadFile/{id}")
	public String downloadFile(@PathVariable("id") String id, HttpServletResponse response) {
		SysFile fileManagement = sysFileService.selectById(id);
		if (fileManagement == null) {
			return "文件丢失";
		}
		try {
			sysFileService.downloadFile(fileManagement, response);
			return "ok";
		} catch (Exception e) {
			log.error("下载文件失败", e);
			return "下载文件失败";
		}
	}

	@RequestMapping("/downloads/{id}")
	public void downloads(@PathVariable("id") String id, HttpServletResponse response) {
		try {
			String idString = id.replaceAll("[\\[\\]]", "").replaceAll("\"", "");
			List<String> ids = new ArrayList<String>();
			if (idString.contains(",")) {
				for (String s : idString.split(","))
					ids.add(s);
			} else
				ids.add(idString);
			if (ids.size() == 1) {
				SysFile fileManagement = sysFileService.selectById(id);
				if (fileManagement == null) {
					return;
				}
				sysFileService.downloadFile(fileManagement, response);
				return;
			}
			String tmpFileName = "下载文件(" + DateUtils.format(new Date()) + ").zip";// 压缩文件名
			try {
				response.setContentType("application/octet-stream;charset=UTF-8");
				response.setHeader("Content-Disposition",
						"attachment;filename=" + java.net.URLEncoder.encode(tmpFileName, "UTF-8"));// .zip
				response.addHeader("Pargam", "no-cache");
				response.addHeader("Cache-Control", "no-cache");

				ZipOutputStream out = new ZipOutputStream(response.getOutputStream());
				for (int i = 0; i < ids.size(); i++) {
					SysFile fileManagement = sysFileService.selectById(ids.get(i));
					if (fileManagement == null) {
						return;
					}
					byte[] byt = sysFileService.getByte(fileManagement);
					out.putNextEntry(new ZipEntry(fileManagement.getFileName()));
					out.write(byt);
				}
				out.flush();
				out.close();
			} catch (Exception e) {
				throw e;
			}
		} catch (Exception e) {
			log.error("下载文件失败", e);
		}
	}

	/**
	 * 批量删除文件
	 * 
	 * @param ids
	 * @return
	 */
	@PostMapping("/delete")
	public R delete(@RequestBody String[] ids) {
		try {
			User user = UserUtil.getUser() == null ? UserUtil.getSystem() : UserUtil.getUser();
			sysFileService.moveFilePath(Arrays.asList(ids), user.getId(), "3");
			return R.ok();
		} catch (Exception e) {
			log.error("删除文件失败delete", e);
			return R.error("删除文件失败");
		}
	}

	/**
	 * 删除文件
	 * 
	 * @param id
	 * @return
	 */
	@PostMapping("/deleteFile/{id}")
	public R deleteFile(@PathVariable("id") String id) {
		try {
			User user = UserUtil.getUser() == null ? UserUtil.getSystem() : UserUtil.getUser();
			List<String> list = new ArrayList<>();
			list.add(id);
			sysFileService.moveFilePath(list, user.getId(), "3");
			return R.ok();
		} catch (Exception e) {
			log.error("删除文件失败delete", e);
			return R.error("删除文件失败");
		}
	}

	/**
	 * 根据业务id查询附件信息
	 * 
	 * @param businessId
	 * @return
	 */
	@GetMapping("/getFileListByBusId/{businessId}")
	public R getFileListByBusId(@PathVariable("businessId") String businessId) {
		try {
			List<SysFile> list = sysFileService.getFileListByBusId(businessId);
			return R.ok().put("fmLIst", list);
		} catch (Exception e) {
			log.error("查询文件列表失败list", e);
			return R.error("查询文件列表失败");
		}
	}

	/**
	 * 根据业务id查询附件数量
	 * 
	 * @param busIds
	 * @return
	 */
	@PostMapping("/getFileCountByBusId")
	public R getFileCountByBusId(@RequestBody String[] busIds) {
		Map<String, Object> fileCount = sysFileService.getFileCountByBusId(busIds);
		return R.ok().put("fileCount", fileCount);
	}
}
